﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "生产详情";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var orderId = ViewBag.OrderId ?? 1;
}

<div class="container-fluid">
    <!-- 页面头部 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-body position-relative">
                    
                    <!-- 标题和元信息 -->
                    <div class="row">
                        <div class="col-md-8">
                            <h4 class="mb-2">生产详情</h4>
                            <h3 class="text-primary mb-3" id="orderName">加载中...</h3>
                            <div class="row">
                                <div class="col-md-6">
                                    <p class="mb-1"><strong>创建人：</strong><span id="creator">加载中...</span></p>
                                    <p class="mb-1"><strong>创建时间：</strong><span id="createTime">加载中...</span></p>
                                </div>
                                <div class="col-md-6">
                                    <p class="mb-1"><strong>最后修改人：</strong><span id="lastModifier">加载中...</span></p>
                                    <p class="mb-1"><strong>修改时间：</strong><span id="modifyTime">加载中...</span></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 d-flex justify-content-end align-items-start">
                            <div class="d-flex flex-column">
                                <button class="btn btn-outline-info mb-2" onclick="testApiConnection()">
                                    <i class="fas fa-plug"></i> 测试API
                                </button>
                                <button class="btn btn-outline-warning mb-2" onclick="debugDataStructure()">
                                    <i class="fas fa-bug"></i> 调试数据
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 报工弹窗 -->
    <div class="modal fade" id="reportModal" tabindex="-1" aria-labelledby="reportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="reportModalLabel">报工</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">工序编号</label>
                        <input type="text" class="form-control" id="rg_activityNumber" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">加工顺序</label>
                        <input type="text" class="form-control" id="rg_processing" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">负责人</label>
                        <input type="text" class="form-control" id="rg_principal" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">所在部门</label>
                        <input type="text" class="form-control" id="rg_department" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">报工数量</label>
                        <input type="number" min="0" class="form-control" id="rg_quantity" placeholder="请输入本次报工数量">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="rg_confirmBtn">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 标签页导航 -->
    <div class="row mb-4">
        <div class="col-12">
            <ul class="nav nav-tabs" id="orderTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="info-tab" data-bs-toggle="tab" data-bs-target="#info" type="button" role="tab" aria-controls="info" aria-selected="true">
                        工单信息
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="report-tab" data-bs-toggle="tab" data-bs-target="#report" type="button" role="tab" aria-controls="report" aria-selected="false">
                        报工记录
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="operation-tab" data-bs-toggle="tab" data-bs-target="#operation" type="button" role="tab" aria-controls="operation" aria-selected="false">
                        操作记录
                    </button>
                </li>
            </ul>
        </div>
    </div>

    <!-- 标签页内容 -->
    <div class="tab-content" id="orderTabsContent">
        <!-- 工单信息标签页 -->
        <div class="tab-pane fade show active" id="info" role="tabpanel" aria-labelledby="info-tab">
            <div class="row">
                <!-- 基础信息 -->
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">基础信息</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">工单编号</label>
                                    <p class="mb-0" id="orderNumber">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">单据时间</label>
                                    <p class="mb-0" id="orderDate">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">销售订单</label>
                                    <p class="mb-0">无</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">负责人</label>
                                    <p class="mb-0" id="principal">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">工单名称</label>
                                    <p class="mb-0" id="orderNameDetail">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">关联生产单号</label>
                                    <p class="mb-0" id="productionNumber">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">关联项目</label>
                                    <p class="mb-0" id="relatedProject">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">所属部门</label>
                                    <p class="mb-0" id="departmentName">加载中...</p>
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label fw-bold">备注</label>
                                    <p class="mb-0 text-muted" id="note">加载中...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 生产物品 -->
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">生产物品</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">产品名称</label>
                                    <p class="mb-0" id="articleName">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">产品编号</label>
                                    <p class="mb-0" id="articleNumber">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">规格型号</label>
                                    <p class="mb-0" id="specifications">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">单位</label>
                                    <p class="mb-0" id="unitName">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">物品类别</label>
                                    <p class="mb-0 text-muted" id="articleType">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">物品分类</label>
                                    <p class="mb-0 text-muted" id="classification">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">计划产量</label>
                                    <p class="mb-0" id="plannedOutput">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">合格数量</label>
                                    <p class="mb-0 text-muted" id="qualifiedNum">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">不良数量</label>
                                    <p class="mb-0 text-muted" id="disqualificationNum">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">合格率</label>
                                    <p class="mb-0 text-muted" id="pass">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">计划开始时间</label>
                                    <p class="mb-0" id="plannedStart">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">实际开始时间</label>
                                    <p class="mb-0" id="actualStart">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">计划结束时间</label>
                                    <p class="mb-0" id="plannedCompletion">加载中...</p>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">实际结束时间</label>
                                    <p class="mb-0" id="actualCompletion">加载中...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 工序流程 -->
                <div class="col-12 mb-4">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">工序流程</h5>
                            <button class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-download"></i> 导出
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead class="table-light">
                                        <tr>
                                            <th width="50">
                                                <input type="checkbox" class="form-check-input" id="selectAllProcess">
                                            </th>
                                            <th width="80">序号</th>
                                            <th width="120">工序编码</th>
                                            <th width="150">工序名称</th>
                                            <th width="100">加工顺序</th>
                                            <th width="200">工艺流程</th>
                                            <th width="100">状态</th>
                                            <th width="120">负责人</th>
                                            <th width="120">所在部门</th>
                                            <th width="200">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="processTbody">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

              
            </div>
        </div>

        <!-- 报工记录标签页 -->
        <div class="tab-pane fade" id="report" role="tabpanel" aria-labelledby="report-tab">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">报工记录</h5>
                    <button class="btn btn-outline-secondary btn-sm">
                        <i class="fas fa-download"></i> 导出
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" class="form-check-input" id="selectAllReport">
                                    </th>
                                    <th width="80">序号</th>
                                    <th width="120">工序编码</th>
                                    <th width="150">工序名称</th>
                                    <th width="100">加工顺序</th>
                                    <th width="200">工艺流程</th>
                                    <th width="120">负责人</th>
                                    <th width="120">所在部门</th>
                                    <th width="100">状态</th>
                                    <th width="120">报工数量</th>
                                    <th width="150">操作</th>
                                </tr>
                            </thead>
                            <tbody id="reportTbody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作记录标签页 -->
        <div class="tab-pane fade" id="operation" role="tabpanel" aria-labelledby="operation-tab">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">操作记录</h5>
                    <div class="d-flex">
                        <button class="btn btn-outline-secondary btn-sm me-3">
                            <i class="fas fa-download"></i> 导出
                        </button>
                        <div class="input-group" style="width: 300px;">
                            <input type="text" class="form-control" placeholder="请搜索" aria-label="搜索">
                            <button class="btn btn-outline-secondary" type="button">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" class="form-check-input" id="selectAllOperation">
                                    </th>
                                    <th width="80">序号</th>
                                    <th width="150">操作人</th>
                                    <th width="200">操作时间</th>
                                    <th width="300">操作内容</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="checkbox" class="form-check-input operation-checkbox"></td>
                                    <td>1</td>
                                    <td>孙十二</td>
                                    <td>2024-06-27 19:15:59</td>
                                    <td>工序1开工</td>
                                </tr>
                                <tr>
                                    <td><input type="checkbox" class="form-check-input operation-checkbox"></td>
                                    <td>2</td>
                                    <td>黄十一</td>
                                    <td>2024-06-27 18:30:08</td>
                                    <td>工序1报工并质检完工</td>
                                </tr>
                                <tr>
                                    <td><input type="checkbox" class="form-check-input operation-checkbox"></td>
                                    <td>3</td>
                                    <td>郑十</td>
                                    <td>2024-06-27 17:05:47</td>
                                    <td>工序2开工</td>
                                </tr>
                                <tr>
                                    <td><input type="checkbox" class="form-check-input operation-checkbox"></td>
                                    <td>4</td>
                                    <td>吴九</td>
                                    <td>2024-06-27 16:10:33</td>
                                    <td>工序2报工并质检</td>
                                </tr>
                                <tr>
                                    <td><input type="checkbox" class="form-check-input operation-checkbox"></td>
                                    <td>5</td>
                                    <td>周八</td>
                                    <td>2024-06-27 15:20:14</td>
                                    <td>工序3开工</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页 -->
                    <div class="row mt-3">
                        <div class="col-md-6 d-flex align-items-center">
                            <span class="text-muted">共36项数据</span>
                            <select class="form-select ms-3" style="width: auto;">
                                <option>5条/页</option>
                                <option>10条/页</option>
                                <option>20条/页</option>
                                <option>50条/页</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <nav aria-label="分页导航">
                                <ul class="pagination justify-content-end mb-0">
                                    <li class="page-item">
                                        <a class="page-link" href="#" aria-label="上一页">
                                            <span aria-hidden="true">&lt;</span>
                                        </a>
                                    </li>
                                    <li class="page-item active">
                                        <a class="page-link" href="#">1</a>
                                    </li>
                                    <li class="page-item">
                                        <a class="page-link" href="#">2</a>
                                    </li>
                                    <li class="page-item">
                                        <a class="page-link" href="#">3</a>
                                    </li>
                                    <li class="page-item">
                                        <a class="page-link" href="#">4</a>
                                    </li>
                                    <li class="page-item">
                                        <a class="page-link" href="#">5</a>
                                    </li>
                                    <li class="page-item">
                                        <a class="page-link" href="#" aria-label="下一页">
                                            <span aria-hidden="true">&gt;</span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .border-dashed {
        border-style: dashed !important;
    }
    
    .nav-tabs .nav-link {
        color: #495057;
        border: none;
        border-bottom: 2px solid transparent;
    }
    
    .nav-tabs .nav-link.active {
        color: #007bff;
        background-color: transparent;
        border-bottom: 2px solid #007bff;
    }
    
    .table th {
        font-size: 0.875rem;
        font-weight: 600;
        background-color: #f8f9fa;
    }
    
    .table td {
        vertical-align: middle;
        font-size: 0.875rem;
    }
    
    .badge {
        font-size: 0.75em;
    }
    
    .form-check-input:checked {
        background-color: #007bff;
        border-color: #007bff;
    }
    
    .btn-sm {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
    }
</style>

<script>
    // 全局变量
    const orderId = @orderId;
    let orderDetailData = null;

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadOrderDetail();
        bindEvents();
        renderReportRecords();
    });

    // 绑定事件
    function bindEvents() {
    // 全选功能
    document.getElementById('selectAllProcess').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.process-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 报工记录全选功能
    document.getElementById('selectAllReport').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.report-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 操作记录全选功能
    document.getElementById('selectAllOperation').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.operation-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    }

    // 加载工单详情数据
    async function loadOrderDetail() {
        try {
            showLoading();
            console.log('开始加载工单详情，ID:', orderId);
            
            const response = await fetch(`/Home/GetOrderDetail/${orderId}`);
            console.log('API响应状态:', response.status);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('工单详情数据响应:', result);

            // 检查API返回的数据结构
            if (result && result.code === 200 && result.data) {
                // API返回成功，数据在result.data中
                orderDetailData = result.data;
                console.log('使用API返回的数据:', orderDetailData);
                renderOrderDetail();
            } else if (result && result.success === false) {
                console.error('API返回错误:', result);
                showError('获取数据失败: ' + (result.message || '未知错误'));
            } else if (result && result.data) {
                // 兼容其他数据结构
                orderDetailData = result.data;
                renderOrderDetail();
            } else {
                // 如果API直接返回数据对象（没有包装结构）
                orderDetailData = result;
                renderOrderDetail();
            }
        } catch (error) {
            console.error('加载工单详情失败:', error);
            showError('加载数据失败: ' + error.message);
        } finally {
            hideLoading();
        }
    }

    // 渲染工单详情
    function renderOrderDetail() {
        if (!orderDetailData) {
            console.error('没有数据可渲染');
            return;
        }

        console.log('开始渲染工单详情数据:', orderDetailData);

        // 渲染工单基本信息
        if (orderDetailData.workOrderForm) {
            const workOrder = orderDetailData.workOrderForm;
            console.log('渲染工单信息:', workOrder);
            
            // 页面头部信息
            document.getElementById('orderName').textContent = workOrder.orderName || '未知工单';
            document.getElementById('creator').textContent = workOrder.principal || '未知';
            document.getElementById('createTime').textContent = formatDateTime(workOrder.createTime) || '未知';
            document.getElementById('lastModifier').textContent = workOrder.principal || '未知';
            document.getElementById('modifyTime').textContent = formatDateTime(workOrder.upDataTime) || '未知';

            // 基础信息
            document.getElementById('orderNumber').textContent = workOrder.orderNumber || '未知';
            document.getElementById('orderDate').textContent = formatDateTime(workOrder.orderDate) || '未知';
            document.getElementById('principal').textContent = workOrder.principal || '未知';
            document.getElementById('orderNameDetail').textContent = workOrder.orderName || '未知';
            document.getElementById('productionNumber').textContent = workOrder.production_Number || '无';
            document.getElementById('relatedProject').textContent = workOrder.related_Project || '无';
            document.getElementById('departmentName').textContent = workOrder.departmentName || '未知';
            document.getElementById('note').textContent = workOrder.note || '无';
        } else {
            console.warn('没有工单信息数据');
        }

        // 渲染物品信息
        if (orderDetailData.articleModel) {
            const article = orderDetailData.articleModel;
            console.log('渲染物品信息:', article);
            
            document.getElementById('articleName').textContent = article.articleName || '未知';
            document.getElementById('articleNumber').textContent = article.articleNumber || '未知';
            document.getElementById('specifications').textContent = article.specifications || '无';
            document.getElementById('unitName').textContent = article.unitName || '无';
            document.getElementById('articleType').textContent = article.articleType || '无';
            document.getElementById('classification').textContent = article.classification || '无';
            document.getElementById('plannedOutput').textContent = article.planned_Output || 0;
            document.getElementById('qualifiedNum').textContent = article.qualifiedNum || 0;
            document.getElementById('disqualificationNum').textContent = article.disqualificationNum || 0;
            document.getElementById('pass').textContent = article.pass || '0%';
            document.getElementById('plannedStart').textContent = formatDateTime(article.planned_Start) || '无';
            document.getElementById('actualStart').textContent = formatDateTime(article.createTime) || '无'; // 使用创建时间作为实际开始时间
            document.getElementById('plannedCompletion').textContent = formatDateTime(article.planned_Completion) || '无';
            document.getElementById('actualCompletion').textContent = formatDateTime(article.upDataTime) || '无'; // 使用更新时间作为实际结束时间
        } else {
            console.warn('没有物品信息数据');
        }

        console.log('工单详情渲染完成');
        // 渲染工序流程
        renderProcessList();
    }

    // 渲染工序流程
    function renderProcessList() {
        const tbody = document.getElementById('processTbody');
        if (!tbody) return;
        tbody.innerHTML = '';

        let processes = orderDetailData.activity_List;
        if (!processes) {
            // 没有工序数据
            const emptyRow = document.createElement('tr');
            emptyRow.innerHTML = `<td colspan="10" class="text-center text-muted">没有工序流程数据</td>`;
            tbody.appendChild(emptyRow);
            return;
        }

        // 兼容对象或数组
        if (!Array.isArray(processes)) {
            processes = [processes];
        }

        processes.forEach((p, idx) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="checkbox" class="form-check-input process-checkbox"></td>
                <td>${idx + 1}</td>
                <td>${p.activity_ListNumber || ''}</td>
                <td>${p.activity_ListName || ''}</td>
                <td>${p.processing ?? ''}</td>
                <td>${p.process_Name || ''}</td>
                <td>${renderStateBadge(p.state)}</td>
                <td>${p.principal || ''}</td>
                <td>${orderDetailData.workOrderForm?.departmentName || ''}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary rg-btn" data-index="${idx}">报工</button>
                </td>
            `;
            tbody.appendChild(row);
        });

        // 绑定报工按钮事件
        document.querySelectorAll('.rg-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                const proc = processes[index];
                openReportModal(proc, this);
            });
        });
    }

    function renderStateBadge(state) {
        switch (state) {
            case '待开始':
            case '下达':
                return '<span class="badge bg-warning">下达</span>';
            case '上线':
                return '<span class="badge bg-info">上线</span>';
            case '开工':
                return '<span class="badge bg-primary">开工</span>';
            case '完成':
                return '<span class="badge bg-success">完成</span>';
            case '关闭':
                return '<span class="badge bg-secondary">关闭</span>';
            default:
                return '<span class="badge bg-light text-dark">-</span>';
        }
    }

    let lastClickedReportButton = null;
    function openReportModal(proc, buttonEl) {
        lastClickedReportButton = buttonEl;
        document.getElementById('rg_activityNumber').value = proc.activity_ListNumber || '';
        document.getElementById('rg_processing').value = proc.processing ?? '';
        document.getElementById('rg_principal').value = proc.principal || '';
        document.getElementById('rg_department').value = orderDetailData.workOrderForm?.departmentName || '';
        document.getElementById('rg_quantity').value = '';

        const modalEl = document.getElementById('reportModal');
        const modal = new bootstrap.Modal(modalEl);
        modal.show();

        // 确定按钮
        const confirmBtn = document.getElementById('rg_confirmBtn');
        // 先移除旧的事件监听
        const newConfirmBtn = confirmBtn.cloneNode(true);
        confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
        newConfirmBtn.addEventListener('click', function() {
            const qty = parseInt(document.getElementById('rg_quantity').value || '0', 10);
            if (isNaN(qty) || qty < 0) {
                alert('请输入有效的报工数量');
                return;
            }
            // TODO: 在此处对接后端报工接口
            const instance = bootstrap.Modal.getInstance(modalEl);
            instance.hide();
            if (lastClickedReportButton) {
                lastClickedReportButton.style.display = 'none';
            }

            // 追加到报工记录
            appendReportRecord({
                activity_ListNumber: proc.activity_ListNumber,
                activity_ListName: proc.activity_ListName,
                processing: proc.processing,
                process_Name: proc.process_Name,
                state: proc.state,
                principal: proc.principal,
                departmentName: orderDetailData.workOrderForm?.departmentName || '',
                quantity: qty
            });
        });
    }

    // 报工记录渲染与追加
    const reportRecords = [];
    function appendReportRecord(record) {
        reportRecords.push(record);
        renderReportRecords();
    }

    function renderReportRecords() {
        const tbody = document.getElementById('reportTbody');
        if (!tbody) return;
        tbody.innerHTML = '';
        if (reportRecords.length === 0) {
            const emptyRow = document.createElement('tr');
            emptyRow.innerHTML = `<td colspan="11" class="text-center text-muted">暂无报工记录</td>`;
            tbody.appendChild(emptyRow);
            return;
        }
        reportRecords.forEach((r, idx) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><input type="checkbox" class="form-check-input report-checkbox"></td>
                <td>${idx + 1}</td>
                <td>${r.activity_ListNumber || ''}</td>
                <td>${r.activity_ListName || ''}</td>
                <td>${r.processing ?? ''}</td>
                <td>${r.process_Name || ''}</td>
                <td>${r.principal || ''}</td>
                <td>${r.departmentName || ''}</td>
                <td>${renderStateBadge(r.state)}</td>
                <td>${r.quantity ?? 0}</td>
                <td><span class="text-muted">—</span></td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 格式化日期时间
    function formatDateTime(dateTimeString) {
        if (!dateTimeString) return '';
        try {
            const date = new Date(dateTimeString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (error) {
            return dateTimeString;
        }
    }

    // 显示加载状态
    function showLoading() {
        // 可以添加加载动画
        console.log('正在加载数据...');
    }

    // 隐藏加载状态
    function hideLoading() {
        // 隐藏加载动画
        console.log('数据加载完成');
    }

    // 显示错误
    function showError(message) {
        alert('错误: ' + message);
    }

    // 测试API连接
    async function testApiConnection() {
        try {
            console.log('开始测试API连接...');
            const directApiUrl = `http://localhost:5299/api/WorkOrder/GetWorkOrderDetailsShow?id=${orderId}`;
            console.log('直接API地址:', directApiUrl);
            
            const response = await fetch(directApiUrl);
            console.log('直接API响应状态:', response.status);
            
            if (response.ok) {
                const data = await response.json();
                console.log('直接API返回数据:', data);
                alert('API连接成功！数据已加载到控制台');
            } else {
                const errorText = await response.text();
                console.error('直接API错误:', errorText);
                alert(`API连接失败: ${response.status}\n错误信息: ${errorText}`);
            }
        } catch (error) {
            console.error('API连接测试失败:', error);
            alert('API连接测试失败: ' + error.message);
        }
    }

    // 调试数据结构
    function debugDataStructure() {
        console.log('=== 数据结构调试 ===');
        console.log('orderId:', orderId);
        console.log('orderDetailData:', orderDetailData);
        
        if (orderDetailData) {
            console.log('orderDetailData.workOrderForm:', orderDetailData.workOrderForm);
            console.log('orderDetailData.articleModel:', orderDetailData.articleModel);
            console.log('orderDetailData.activity_List:', orderDetailData.activity_List);
            
            if (orderDetailData.workOrderForm) {
                console.log('工单信息字段:');
                Object.keys(orderDetailData.workOrderForm).forEach(key => {
                    console.log(`  ${key}:`, orderDetailData.workOrderForm[key]);
                });
            }
            
            if (orderDetailData.articleModel) {
                console.log('物品信息字段:');
                Object.keys(orderDetailData.articleModel).forEach(key => {
                    console.log(`  ${key}:`, orderDetailData.articleModel[key]);
                });
            }
        } else {
            console.log('orderDetailData 为空');
        }
        
        alert('数据结构调试信息已输出到控制台');
    }
</script>
